package com.appfuse.spring.lab.webapp.controller;

import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.appfuse.service.GenericManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.appfuse.spring.lab.webapp.manager.AdjuntoManager;
import com.appfuse.spring.lab.webapp.model.Adjunto;
import com.appfuse.spring.lab.webapp.util.JsonResponse;


/**
 * Simple class to retrieve a list of users from the database.
 * <p/>
 * <p>
 * <a href="UserController.java.html"><i>View Source</i></a>
 * </p>
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
@Controller
@RequestMapping("/filelist*")
public class FileAdminController extends BaseFormController {
	
	@Autowired
	private AdjuntoManager adjuntoManager;	
	
	@Autowired
	private GenericManager<Adjunto, Long> genericAdjuntoManager;  	
	
	@RequestMapping(method = RequestMethod.GET)
    public ModelAndView handleRequest(HttpServletRequest request, @RequestParam(required = false, value = "q") String query) throws Exception {
		
		String userName = (String)request.getRemoteUser();
		
		Map<String, Object> params = new TreeMap<String, Object>();
		params.put("1", userName);
		
		return new ModelAndView("fileList", "fileList", adjuntoManager.findByNamedQuery(Adjunto.NAMED_QUERY_SELECT_USER_FILES, params));
    }
	
	@RequestMapping(value="/delete", method=RequestMethod.POST)
	public @ResponseBody JsonResponse delete(@RequestParam(required = false, value = "id") String id, HttpServletRequest request)
	{
		genericAdjuntoManager.remove(Long.parseLong(id));
		saveMessage(request, getText("upload.delete", request.getLocale()));
        JsonResponse res = new JsonResponse();
        res.setStatus("SUCCESS_Adjuto");        
        return res;
	}
	
	@RequestMapping(value="/download", method=RequestMethod.GET)
	public ModelAndView download(@RequestParam(required = false, value = "id") String id, HttpServletResponse response) throws Exception {
    	
		Adjunto adjunto = genericAdjuntoManager.get(Long.parseLong(id));
 
        response.setContentType(adjunto.getContentType());
        response.setContentLength(adjunto.getBlAdjunto().length);
        response.setHeader("Content-Disposition","attachment; filename=\"" + adjunto.getOriginalFileName() +"\"");
 
        FileCopyUtils.copy(adjunto.getBlAdjunto(), response.getOutputStream());
 
        return null;
     
    } 	
	
}
